/*
 * PetRewardResource.cpp
 *
 *  Created on: 2013. 9. 9.
 *      Author: mega@gamevil.com
 */

#include "../User.h"
#include "PetRewardResource.h"
#include "../NUtil/Utils.h"
#include "../engine.h"

namespace ProjectZ { namespace NResource {

PetRewardResource::PetRewardResource()
{
	pPetRewardAndroid	= new PetRewardData;
	pPetRewardIOS		= new PetRewardData;
}

PetRewardResource::~PetRewardResource()
{
	delete pPetRewardAndroid;
	delete pPetRewardIOS;
}

bool PetRewardResource::LoadResource()
{
	if (false == pPetRewardAndroid->LoadResource(MARKET_GOOGLE, SC_KAKAO_GOOGLE))
		return false;

	if (false == pPetRewardIOS->LoadResource(MARKET_IOS, SC_KAKAO_IOS))
		return false;

	return true;
}

PetRewardData::Flyweight * PetRewardResource::GetFly(int company, int saleCode, int level)
{
	NUtil::MarketType marketType = NUtil::GetMarketType(company, saleCode);

	switch (marketType)
	{
	case NUtil::MarketType::AD_KAKAO:
		return pPetRewardAndroid->GetFly(level);

	case NUtil::MarketType::IOS_KAKAO:
		return pPetRewardIOS->GetFly(level);

	default:
		return NULL;
	}

	return NULL;
}

PetRewardData::~PetRewardData()
{
	std::for_each(clsFlyTree.begin(), clsFlyTree.end(), ProjectZ::NUtil::del_second_ptr<DATATREE::value_type>);
}

bool PetRewardData::LoadResource(int company, int saleCode)
{
	::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
	clsAuto->SetQueryType(::Database::Command::SELECT);
	clsAuto->MakeQuery("SELECT * FROM resource_battlepet_reward WHERE company=%d AND sale_cd=%d", company, saleCode);

	if (false == ::Database::GETSESSION()->SyncExecute(1, clsAuto))
		return false;

	if( clsAuto->GetErrorIdx() != 0 )
		return false;

	if (0 == clsAuto->ResultRowCount())
		return false;

	while( clsAuto->Next() )
	{
		::Toolkit::Str<3> NATIONAL_CODE;
		int seq;
		int tmp_company;
		int tmp_salecode;

		PetRewardData::Flyweight * pFly = new PetRewardData::Flyweight;

		clsAuto->GetRecord() >> NATIONAL_CODE >> seq >> tmp_company >> tmp_salecode
				>> pFly->_PC_LEVEL >> pFly->_R_PET1 >> pFly->_R_PET2
				>> pFly->_R_PET3 >> pFly->_R_PET4 >> pFly->_R_PET_MIN_LV >> pFly->_R_PET_MAX_LV;

		if (0 != Config::Instance().GetResourceDatabase()._strNational.compare(NATIONAL_CODE.c_str()))
		{
			DEBUGLOG("%s:%d NATIONAL_CODE ERROR!!! Config National Code [%s] , Resource National Code [%s]",
					__FILE__, __LINE__,
					Config::Instance().GetResourceDatabase()._strNational.c_str(),
					NATIONAL_CODE.c_str());
			return false;
		}

		clsFlyTree[pFly->_PC_LEVEL] = pFly;
	}

	return true;
}


PetRewardData::Flyweight * PetRewardData::GetFly(int level)
{
	int levelRange = (level / 10) * 10;

	if (levelRange <= 0)
		levelRange = 1;

	auto iter = clsFlyTree.find(levelRange);

	if (iter == clsFlyTree.end())
		return NULL;

	return iter->second;
}

} /* NResource */ } /* ProjectZ */
